import { Button, Card, Form, Input, message, Select, Space, Table } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { useCallback, useEffect, useState } from "react";
import {
  reqGetCityOrDistrict,
  reqGetHospital,
  reqGetHosType,
  reqGetProvince,
  reqUpdateHospitalStatus,
} from "@/api/hospital/hospitalList";
import {
  HospitalItems,
  ProvinceItems,
} from "@/api/hospital/model/hospitalListTypes";
import { useNavigate } from "react-router-dom";

const { Option } = Select;

export default function HospitalList() {
  //声明一下
  let [form] = Form.useForm();
  
  //表单完成的回调
  let finish = async () => {
    //获取表单元素的值
    let res = form.getFieldsValue();
    //更新状态
    setFields(res);    
  };

  //结构
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 70,
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render: (value) => {
        return (
          <img alt="" width="60" src={`data:image/png;base64, ${value}`} />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院等级",
      render: (value) => {
        return value.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (value) => {
        return value.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value) => {
        return value ? "已上线" : "已下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      fixed: "right",
      width: 250,
      render: (value) => {
        return (
          <Space>
            <Button type="primary" onClick={() => {
              navigate(`/syt/hospital/hospitalList/show/${value.id}`);
            }}>查看</Button>
            <Button type="primary" onClick={() => {
              navigate(`/syt/hospital/hospitalList/schedule/${value.hoscode}`);
            }}>排班</Button>
            <Button onClick={async () => {
              //更新
              await reqUpdateHospitalStatus(value.id, value.status ? 0 : 1);
              //提示
              message.success('更新成功');
              //更新列表
              // getHospital(); //这个是可以的
              let newHospital = hospital.map(item => {
                if(item.id === value.id){
                  item.status = item.status ? 0 : 1
                };
                return item;
              })
              //更新状态
              setHospital(newHospital);
            }} type="primary">{value.status ? '下线' : '上线'}</Button>
          </Space>
        );
      },
    },
  ];

  //声明状态 省市县
  let [province, setProvince] = useState<ProvinceItems>([]);
  let [city, setCity] = useState<ProvinceItems>([]);
  let [district, setDistrict] = useState<ProvinceItems>([]);
  //声明状态 管理医院类型
  let [hosType, setHosType] = useState<ProvinceItems>([]);
  //声明与分页相关的状态
  let [current, setCurrent] = useState<number>(1);
  let [total, setTotal] = useState<number>(0);
  let [pageSize, setPageSize] = useState<number>(5);
  //设置医院信息的状态
  let [hospital, setHospital] = useState<HospitalItems>([]);
  //加载中状态
  let [loading, setLoading] = useState(false);
  //声明状态
  let [fields, setFields] = useState<any>({
    cityCode: undefined,
    districtCode: undefined,
    hoscode: undefined,
    hosname: undefined,
    hostype: undefined,
    provinceCode: undefined,
    status: undefined,
  });

  //声明 effect 组件挂载完毕之后, 获取省份信息
  useEffect(() => {
    let getProvince = async () => {
      let res = await reqGetProvince();
      //更新状态
      setProvince(res);
    };
    getProvince();
  }, []);

  //当省份信息发生变化时的事件回调
  let getCity = async (provinceId: number) => {
    //判断 provinceId 如果为空则返回
    if (!provinceId) return;
    //修改城市与区域的值
    form.setFieldsValue({ districtCode: undefined, cityCode: undefined });
    //清空区县与城市的列表
    setDistrict([]);
    setCity([]);
    //获取城市的信息
    let citys = await reqGetCityOrDistrict(provinceId);
    //更新状态
    setCity(citys);
  };

  //当城市信息发生变化的时候, 事件回调
  let getDistrict = async (cityId: number) => {
    //修改县区的值
    form.setFieldsValue({ districtCode: undefined });
    //清空区县的列表
    setDistrict([]);
    //获取区域的信息
    let district = await reqGetCityOrDistrict(cityId);
    //更新状态
    setDistrict(district);
  };

  //声明 effect 组件挂载完毕之后, 获取医院类型信息
  useEffect(() => {
    let getHosType = async () => {
      let res = await reqGetHosType();
      //更新状态
      setHosType(res);
    };
    getHosType();
  }, []);

  //声明函数发送请求 获取医院信息
  let getHospital = useCallback(async () => {
    setLoading(true);
    //获取医院的数据
    let result = await reqGetHospital({
      page: current,
      limit: pageSize,
      ...fields,
    });
    //设置医院状态数据
    setHospital(result.content);
    //更新数据的总述
    setTotal(result.totalElements);
    //设置加载完毕
    setLoading(false);
  }, [current, pageSize, fields]);

  //声明 effect 组件挂载完毕, 获取医院的信息
  useEffect(() => {
    //调用
    getHospital();
  }, [getHospital]);

  //获得 navigate 函数
  let navigate = useNavigate();

  return (
    <Card>
      {/* 表单部分 */}
      <Form layout="inline" form={form} onFinish={finish}>
        <Form.Item name="provinceCode" style={{ width: 200, marginBottom: 20 }}>
          <Select placeholder="请选择省" allowClear onChange={getCity}>
            {province.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 200 }}>
          <Select placeholder="请选择市" allowClear onChange={getDistrict}>
            {city.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 200 }}>
          <Select placeholder="请选择区" allowClear>
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>

        <Form.Item name="hostype" style={{ width: 200 }}>
          <Select placeholder="医院类型" allowClear>
            {hosType.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status" style={{ width: 200 }}>
          <Select placeholder="医院状态" allowClear>
            <Option value={1}>已上线</Option>
            <Option value={0}>已下线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button>清空</Button>
        </Form.Item>
      </Form>
      <div className="h-20"></div>
      {/* 表格部分 */}
      <Table
        loading={loading}
        rowKey={"id"}
        dataSource={hospital}
        columns={columns}
        bordered
        scroll={{
          x: 1300,
        }}
        pagination={{
          total: total,
          pageSize: pageSize,
          current,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [2, 4, 6, 10],
          showTotal: (total) => {
            return `总计 ${total} 条`;
          },
          //当页码或者是每页显示数量, 发生变化的时候, 会触发 onChange
          onChange: (page: number, pageSize: number) => {
            //更新状态
            setCurrent(page);
            setPageSize(pageSize);
          },
        }}
      />
    </Card>
  );
}
